package com.oasistudio.tk.connector.imp;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class HotSearchKeywords{
	public static final int TIMEOUT = 10000;

	public HotSearchKeywords(){
	}
	
	public String getApiUrl() {
		StringBuilder sb = new StringBuilder("http://www.cloudmenu.cn:8080/taobaoke/hotwords?command=query");
		String url = sb.toString();
		System.out.println("HotSearchKeywords.getApiUrl() url="+url);
		return url;
	}
	
	public List<String> syncConnect() {
		try {
			long startTime = System.currentTimeMillis();
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(new URI(getApiUrl()));
			HttpResponse response = client.execute(request);
			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			int i = 0;
			DataInputStream dis = new DataInputStream(response.getEntity().getContent());
			byte[] b = new byte[2048];
			while ((i = dis.read(b, 0, 2048)) != -1) {
				// System.out.println("mellon:ApiConnector.syncConnect() "+i+" bytes response data readed!");
				bs.write(b, 0, i);
				if (System.currentTimeMillis() - startTime > TIMEOUT * 4) {
					bs.reset();
					break;
				}
			}
			return this.syncPaser(bs.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ArrayList<String>();
	}
	
	public List<String> syncPaser(byte[] all) {
		List<String> keywords = new ArrayList<String>();
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		try {
			String str = new String(all, "UTF-8");
			if(str!=null && str.trim().length()>0){
				String[] keywordsArray = str.split(",");
				for(String keyword : keywordsArray){
					keywords.add(keyword);
				}
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return keywords;
	}
}



